#include "EthInitHelper.h"

void Lwip_Bsp_Init() {
	// 初始化以太网芯片
	;//GPIO_ResetPins(ETH_RST1_PORT, ETH_RST1_PIN);
	rt_thread_mdelay(50);
	;//GPIO_SetPins(ETH_RST1_PORT, ETH_RST1_PIN);
	SWDT_FeedDog();
	rt_thread_mdelay(50);
	
  LL_PERIPH_WE(LL_PERIPH_ALL);
  
	
  // 初始化LWIP
  lwip_init();
	SWDT_FeedDog();
	

  /* Configure the Network interface */
  Netif_Config();
	SWDT_FeedDog();
  /* Register write protected for some required peripherals. */
  LL_PERIPH_WP(LL_PERIPH_ALL);

  /* Notify user about the network interface config */
  EthernetIF_NotifyConnStatus(&gnetif);
	SWDT_FeedDog();
	

  // 获取链接列表中的第一个netif结构
  struct netif *netif_node;
  netif_node = netif_list;
  while (netif_node != NULL) {
    // 输出网卡的状态，例如IP地址、子网掩码等
    // 这里需要根据你的需求和环境进行具体的实现
    rt_kprintf("Netif IP Address: %s\n", ipaddr_ntoa(&netif_node->ip_addr));
    rt_kprintf("Netif Subnetmask: %s\n", ipaddr_ntoa(&netif_node->netmask));
    rt_kprintf("Netif Gateway: %s\n", ipaddr_ntoa(&netif_node->gw));
    rt_kprintf("Netif Link Status: %s\n", (netif_is_link_up(netif_node) ? "Up" : "Down"));

    // 获取下一个netif结构
    netif_node = netif_node->next;
	  SWDT_FeedDog();
	  
  }
  
}

void Netif_Config(void) {
  ip_addr_t ipaddr;
  ip_addr_t netmask;
  ip_addr_t gw;

#ifdef USE_DHCP
  ip_addr_set_zero_ip4(&ipaddr);
  ip_addr_set_zero_ip4(&netmask);
  ip_addr_set_zero_ip4(&gw);
#else
  IP_ADDR4(&ipaddr, IP_ADDR0, IP_ADDR1, IP_ADDR2, IP_ADDR3);
  IP_ADDR4(&netmask, NETMASK_ADDR0, NETMASK_ADDR1, NETMASK_ADDR2, NETMASK_ADDR3);
  IP_ADDR4(&gw, GW_ADDR0, GW_ADDR1, GW_ADDR2, GW_ADDR3);
#endif /* USE_DHCP */
  /* Add the network interface */
  (void) netif_add(&gnetif, &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &ethernet_input);
  /*  Registers the default network interface */
  netif_set_default(&gnetif);

  if (netif_is_link_up(&gnetif)) {
    /* When the netif is fully configured this function must be called */
    rt_kprintf("set default netif\n");
    netif_set_up(&gnetif);
  } else {
    /* When the netif link is down this function must be called */
    netif_set_down(&gnetif);
  }
  /* Set the link callback function, this function is called on change of link status*/
  netif_set_link_callback(&gnetif, EthernetIF_LinkCallback);
}

void ETH_LinkIrqCallback(void) {
  if (SET == EXTINT_GetExtIntStatus(EXTINT_CH03)) {
    EthernetIF_UpdateLink(&gnetif);
    EXTINT_ClearExtIntStatus(EXTINT_CH03);
  }
}
